#!/usr/bin/env python3

import sys
import os
import csv

# _BASE_DIR is the root directory of the tool and needs to be added to sys.path.
_BASE_DIR = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(_BASE_DIR)

from common.logger import log
from framework.report.var_report import JSONFileKey as Key, PdfContentEN as PcEN
from framework.report.base_report import Report


class CSVReport(Report):
    def __init__(self, file_name, test_data):
        super().__init__(file_name, test_data)
        self.score = self.bm_summary.get(Key.SCORE)

    def get_suite_summary(self):
        title_row = [PcEN.TEST_SUITES, PcEN.DESC, PcEN.SCORE]
        self.story.append(title_row)

        for suite_name, summary_info in self.bm_suite.items():
            for sub_suite_name, sub_suite_info in summary_info.items():
                if sub_suite_name in [Key.DESC, Key.SCORE]:
                    continue
                suite_res = [sub_suite_name, sub_suite_info.get(Key.DESC), sub_suite_info.get(Key.SCORE)]
                self.story.append(suite_res)
            self.story.append([suite_name, summary_info.get(Key.DESC), summary_info.get(Key.SCORE)])
        self.story.append([])

    def get_workloads(self, wd_data, table_title=None):
        blank_line = False
        for wd_name, wd_info in wd_data.items():
            wd_dict = wd_info.get(Key.WORKLOADS)
            if not wd_dict:
                continue
            if blank_line:
                self.story.append([])

            if table_title:
                self.story.append(table_title)
                wd_title = [wd_name, "", "", "", "", ""]
                self.story.append(wd_title)
                suite_name = ""
                wd_score = ["", "", wd_name, "", "", wd_info.get(Key.INDEX)]
            else:
                suite_name = wd_name
                wd_score = ["", "", PcEN.SUITE_TOTAL_SCORE.format(wd_name), "", "", "", wd_info.get(Key.SCORE)]

            for name, workload_msg in wd_dict.items():
                if table_title:
                    wd_row = [suite_name, name, workload_msg.get(Key.DESC), workload_msg.get(Key.SCORE),
                              workload_msg.get(Key.UNIT), workload_msg.get(Key.INDEX)]
                else:
                    wd_row = [suite_name, name, workload_msg.get(Key.DESC), workload_msg.get(Key.ELAPSED_TIME),
                              workload_msg.get(Key.SCORE), workload_msg.get(Key.UNIT), workload_msg.get(Key.INDEX)]
                self.story.append(wd_row)
                suite_name = ""
            self.story.append(wd_score)
            blank_line = True
        if not table_title or blank_line:
            self.story.append([])

    def get_suite_detail(self):
        title_row = [PcEN.TEST_SUITES, PcEN.TEST_CASES, PcEN.DESC, PcEN.SECONDS, PcEN.SCORE, PcEN.UNIT, PcEN.INDEX]
        self.story.append(title_row)
        for suite_info in self.bm_data.values():
            self.get_workloads(suite_info)

    def get_sub_items(self):
        title_row = [PcEN.WORKLOADS, PcEN.SUB_ITEMS, PcEN.DESC, PcEN.SCORE, PcEN.UNIT, PcEN.INDEX]
        self.get_workloads(self.bm_sub_item, title_row)

    def get_testcase_status(self):
        status_dict = super().get_testcase_status()
        for status_key, status_value in status_dict.items():
            self.story.append([status_key, status_value])

    def get_report_content(self):
        self.get_suite_summary()
        self.get_suite_detail()
        self.get_sub_items()
        self.get_testcase_status()

    def make_report(self):
        log.info("Start creating csv report.")
        try:
            self.get_report_content()
            with open(self.file_name, "w", newline="") as file:
                writer = csv.writer(file)
                for row in self.story:
                    writer.writerow(row)
            log.info("Create csv success.")
        except Exception as err:
            log.error("Create csv fail, %s" % err)

